//
//  ImageDetailsViewController.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/5/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import "ImageDetailsViewController.h"

#import "Event.h"
#import "Evidence.h"

#import "EXF.h"

@implementation ImageDetailsViewController

@synthesize evidenceToBeDisplayed = _evidenceToBeDisplayed;
@synthesize evidenceMetadataFetchedResultController = _evidenceMetadataFetchedResultController;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.toolbarHidden = NO;
    
    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStyleBordered target:self action:@selector(closeForDetails)];
    
    self.navigationItem.rightBarButtonItem = closeButton;
    
    [self refineTitle];
    
    [closeButton release];
    
    [self.tableView reloadData];
    
    eventNameField = [[UITextField alloc] init];
    eventNameField.autoresizingMask = ( UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin );
    eventNameField.placeholder = @"Event name";
    eventNameField.tag = 100;
    eventNameField.delegate = self;
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    self.evidenceToBeDisplayed = nil;
    
}

- (void)dealloc
{
    [_evidenceToBeDisplayed release];
    [eventNameField release];
    
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[[self.evidenceMetadataFetchedResultController sections] lastObject] numberOfObjects] ? 2 : 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (section == 1) ? [[[self.evidenceMetadataFetchedResultController sections] lastObject] numberOfObjects] : 3 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        eventNameField.frame = CGRectMake(cell.bounds.size.width * 0.35, cell.bounds.size.height * 0.3, cell.bounds.size.width * 0.7, cell.bounds.size.height * 0.6);
        
    } else {
        id aControlObject = [cell viewWithTag:100];
        if (aControlObject != nil) {
            [aControlObject removeFromSuperview];
        }
    }
    
    // Configure the cell...
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"Name";
            if (self.evidenceToBeDisplayed.evidenceName != nil) {
                eventNameField.text = self.evidenceToBeDisplayed.evidenceName;
            }
            [cell addSubview:eventNameField];
        } else if (indexPath.row == 1) {
            cell.textLabel.text = @"Timestamp";
            if (self.evidenceToBeDisplayed.datetimeCollected != nil) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [[SLCommonsDateUtility localDefaultDateTimeFormat:SLCommonsDateUtilityDateTimeFormatLongFormat] stringFromDate:self.evidenceToBeDisplayed.datetimeCollected]];
            } else {
                cell.detailTextLabel.text = @"-";
            }
            
        } else if (indexPath.row == 2) {
            cell.textLabel.text = @"Belong to";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", self.evidenceToBeDisplayed.belongToEvents.eventName];
        }
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 3) {
        return 150;
    } else {
        return 44;
    }
}

- (NSFetchedResultsController *)evidenceMetadataFetchedResultController
{
    if (_evidenceMetadataFetchedResultController != nil) {
        return _evidenceMetadataFetchedResultController;
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    fetchRequest.entity = [NSEntityDescription entityForName:@"EvidenceMeta" inManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]];
    fetchRequest.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"defineTimestamp" ascending:NO], nil];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"belongToEvidence = %@", self.evidenceToBeDisplayed];
    
    NSFetchedResultsController *fetchResultControl = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext] sectionNameKeyPath:nil cacheName:nil];
    
    self.evidenceMetadataFetchedResultController = fetchResultControl;
    
    [fetchRequest release];
    [fetchResultControl release];
    
    return _evidenceMetadataFetchedResultController;
}

#pragma mark - Implement method
- (void)closeForDetails
{
    [self.navigationController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    
    UITextField *newEventName = (UITextField *) [[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]] viewWithTag:100];
    
    // reassigned evidence name
    if ([newEventName.text length] > 0 && ![newEventName.text isEqualToString:self.evidenceToBeDisplayed.evidenceName]) {
        self.evidenceToBeDisplayed.evidenceName = newEventName.text;
    }
    
    // Save meta data
    NSError *error = nil;
    [[[SRConnectionControlCenter sharedInstance] manageObjectContext] save:&error];
    if (error != nil) {
        NSLog(@"%s Error while saving evidence meta data: %@", __PRETTY_FUNCTION__, [error localizedDescription]);
    }
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void)refineTitle
{
    self.title = (self.evidenceToBeDisplayed.evidenceName != nil) ? [NSString stringWithFormat:@"%@", self.evidenceToBeDisplayed.evidenceName] : [NSString stringWithFormat:@"%@", self.evidenceToBeDisplayed.filename] ;
}

@end
